package com.ibuonline.b2b.gather;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DataGatherServer extends Thread {
	static final int PORT = 8899;
	//static final String SAVE_DIR = "/usr/local/www/img1/art/";
	static final String SAVE_DIR = "C:/upload/temp/art/";
	
	public void run() {
		ServerSocket server = null;
		try {
			String yyyymm = new SimpleDateFormat("yyyyMM").format(new Date());
			File dir = new File(SAVE_DIR + yyyymm + "/");
			if (!dir.exists())
				dir.mkdirs();
			server = new ServerSocket(PORT);
			while (true) {
				Socket client = null;
				BufferedOutputStream bos = null;
				BufferedInputStream bis = null;
				try {
					client = server.accept();
					bos = new BufferedOutputStream(new FileOutputStream(SAVE_DIR + System.currentTimeMillis() + ".zip"));
					bis = new BufferedInputStream(client.getInputStream());
					byte[] b = new byte[8096];
					int i;
					while ((i = bis.read(b)) != -1) 
						bos.write(b, 0, i);
					bos.close();
					bis.close();
				} catch(Exception e) {
					e.printStackTrace();
				} finally {
					if (client != null)
						client.close();
					if (bos != null)
						bos.close();
					if (bis != null)
						bis.close();
				}
			}			
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (server != null)
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		new DataGatherServer().start();
	}
}
